package edu.seu.mart.controller;

import edu.seu.mart.service.IMsgService;
import edu.seu.mart.utils.SecurityKit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 微信控制器类
 */
@Controller
@RequestMapping("/weixin")
public class WeixinController {

    private static final String TOKEN = "allsky";

    @Resource
    private IMsgService msgService;

    @RequestMapping(method = RequestMethod.GET)
    public void wget(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /**
         * signature 微信加密签名
         * timestamp 时间戳
         * nonce 随机数
         * echostr 随机字符串
         */
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        /**
         * 1. 将token、timestamp、nonce三个参数进行字典序排序
         */
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        /**
         * 2. 将三个参数字符串拼接成一个字符串进行sha1加密
         */
        StringBuilder sb = new StringBuilder();
        for (String str : arr) {
            sb.append(str);
        }
        String sha1Msg = SecurityKit.encryption(sb.toString());
        /**
         * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
         */
        if (signature.equals(sha1Msg)) {
            resp.getWriter().println(echostr);
        }
    }

    /**
     * 处理微信服务器发来的消息
     */
    @RequestMapping(method = RequestMethod.POST)
    public void wpost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置请求、响应的编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 获取消息并响应
        String respMsg = msgService.process(req.getInputStream());
        resp.getWriter().print(respMsg);
    }
}
